package net.zoneland.knowledge.service.impl.search;

import java.util.List;
import java.util.stream.Collectors;

import org.apache.commons.collections4.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import net.zoneland.knowledge.dao.FavoriteMapper;
import net.zoneland.knowledge.model.EsQuestion;
import net.zoneland.knowledge.model.Favorite;
import net.zoneland.knowledge.model.FavoriteExample;
import net.zoneland.knowledge.service.EsService;

/**
 * 我的收藏.
 *
 * @author: bcc
 * 2021/5/26
 */
@Service("searchOperationImplQueryFavorite")
public class SearchOperationImplQueryFavorite extends AbstractSearchOperation {

    /**
     * logger.
     */
    private static final Logger LOGGER = LoggerFactory.getLogger(SearchOperationImplQueryFavorite.class);

    @Autowired
    private FavoriteMapper favoriteMapper;

    @Autowired
    private EsService esService;

    @Override
    public boolean needRun(final SearchDto searchDto) {
        if (null != searchDto.getQaQueryDto() && "我的收藏".equals(searchDto.getQaQueryDto().getQueryText())) {
            return true;
        }
        return false;
    }

    @Override
    protected void doSearchOrDeal(final SearchDto searchDto) throws Exception {
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("start SearchOperationImplQueryFavorite {}", searchDto);
        }
        List<EsQuestion> result = null ;
        final FavoriteExample example = new FavoriteExample();
        example.createCriteria().andCreatorUidEqualTo(searchDto.getQaQueryDto().getLoginUserPojo().getUserID())
                .andEnabledEqualTo(true)
                .andCategoryEqualTo(searchDto.getQaQueryDto().getCategoryList());
        final List<Favorite> favorites = favoriteMapper.selectByExample(example);
        try {
            if (CollectionUtils.isNotEmpty(favorites)) {
                final List<String> esIds = favorites.stream()
                    .map(Favorite::getEsQuestionId)
                    .collect(Collectors.toList());
                result = esService.getValidEsQuestionByIds(esIds);
            }
            searchDto.setEsQuestions(result);
            searchDto.setStopSearch(true);
        } catch (Exception e) {
            searchDto.setErrorFlag(true);
            LOGGER.error("SearchOperationImplQueryFavorite error", e);
        }
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("end SearchOperationImplQueryFavorite {}", searchDto);
        }
    }



}
